package com.sdu.shanyimisapi.service.impl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.sdu.shanyimisapi.common.PageUtils;
import com.sdu.shanyimisapi.db.dao.WxUserDao;
import com.sdu.shanyimisapi.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lihaopeng
 * @version 1.0
 * @project shanyi-mis-api
 * @description 用户
 * @since 2024/4/13 22:03
 */
@Service
@Slf4j // 加上这个注解，就可以在这个类里做日志输出了，使用log.info()、log.error()等方法
public class UserServiceImpl implements UserService {

    @Resource
    private WxUserDao wxUserDao;


    /**
     * 分页查询用户
     *
     * @param param
     * @return
     */
    @Override
    public PageUtils searchByPage(Map param) {
        ArrayList<HashMap> list = null;
        long count = wxUserDao.countUser(param);
        if (count > 0) {
            list = wxUserDao.searchByPage(param);
        } else {
            list = new ArrayList<>(); // 如果没有数据，就返回一个空的ArrayList
        }
        int page = MapUtil.getInt(param, "page");
        int length = MapUtil.getInt(param, "length");
        PageUtils pageUtils = new PageUtils(list, count, page, length);
        return pageUtils;
    }

    /**
     * 根据ID查询用户
     *
     * @param id 用户id
     * @return
     */
    @Override
    public HashMap searchById(int id) {
        HashMap map = wxUserDao.searchById(id);
        JSONArray likes = JSONUtil.parseArray(MapUtil.getStr(map, "likes"));
        map.replace("likes", likes);
        JSONArray dislikes = JSONUtil.parseArray(MapUtil.getStr(map, "dislikes"));
        map.replace("dislikes", dislikes);
        JSONArray diseases = JSONUtil.parseArray(MapUtil.getStr(map, "diseases"));
        map.replace("diseases", diseases);
        return map;
    }
}
